package com.yxb.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @PackgeName: com.yxb.gateway.filter
 * @ClassName: MyParamGatewayfilterFactory
 * @Author: CongR
 * Date: 2021/3/23 16:14
 * project name: springcloud
 * @Version:
 * @Description: 类名跟配置文件中的myparam 一致 就可以了  后面必须跟上GatewayFilterFactory
 * 自定义局部过滤器
 */
@Component
public class MyParamGatewayFilterFactory extends AbstractGatewayFilterFactory<MyParamGatewayFilterFactory.Config> {

    static final String PARAM_NAME = "param";

    public MyParamGatewayFilterFactory() {
        super(Config.class);
    }

    public List<String> shortcutFieldOrder() {
//        return Arrays.asList("name", "value");
        return Arrays.asList(PARAM_NAME);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange,chain)-> {
            //获取请求参数中param对应的参数名的参数值
            ServerHttpRequest request = exchange.getRequest();
            if (request.getQueryParams().containsKey(config.param)){
                request.getQueryParams().get(config.param).forEach(
                        value -> System.out.printf("-------------局部过滤器------%s = %s---------",config.param,value));
            }
            return chain.filter(exchange);
        };
    }

    public static class Config{
        private String param;

        public String getParam() {
            return param;
        }

        public void setParam(String param) {
            this.param = param;
        }
    }
}
